home *** CD-ROM | disk | FTP | other *** search
/ C & C++ Multimedia Cyber Classroom / C and C++ Multimedia Cyber Classroom (Prentice Hall) (1998).iso / src / fig12_04.jar / Ch12 / Fig12_04 / Tstack1.h < prev   
C/C++ Source or Header  |  1997-10-30  |  2KB  |  56 lines

  1. // Fig. 12.3: tstack1.h
  2. // Class template Stack
  3. #ifndef TSTACK1_H
  4. #define TSTACK1_H
  5.  
  6. #include <iostream.h>
  7.  
  8. template< class T >
  9. class Stack {
  10. public:
  11.    Stack( int = 10 );    // default constructor (stack size 10)
  12.    ~Stack() { delete [] stackPtr; } // destructor
  13.    bool push( const T& ); // push an element onto the stack
  14.    bool pop( T& );        // pop an element off the stack
  15. private:
  16.    int size;             // # of elements in the stack
  17.    int top;              // location of the top element
  18.    T *stackPtr;          // pointer to the stack
  19.  
  20.    bool isEmpty() const { return top == -1; }      // utility
  21.    bool isFull() const { return top == size - 1; } // functions
  22. };
  23.  
  24. // Constructor with default size 10
  25. template< class T >
  26. Stack< T >::Stack( int s )
  27. {
  28.    size = s > 0 ? s : 10;  
  29.    top = -1;               // Stack is initially empty
  30.    stackPtr = new T[ size ]; // allocate space for elements
  31. }
  32.  
  33. // Push an element onto the stack
  34. // return 1 if successful, 0 otherwise
  35. template< class T >
  36. bool Stack< T >::push( const T &pushValue )
  37. {
  38.    if ( !isFull() ) {
  39.       stackPtr[ ++top ] = pushValue; // place item in Stack
  40.       return true;  // push successful
  41.    }
  42.    return false;     // push unsuccessful
  43. }
  44.  
  45. // Pop an element off the stack
  46. template< class T > 
  47. bool Stack< T >::pop( T &popValue )
  48. {
  49.    if ( !isEmpty() ) {
  50.       popValue = stackPtr[ top-- ];  // remove item from Stack
  51.       return true;  // pop successful
  52.    }
  53.    return false;     // pop unsuccessful
  54. }
  55.  
  56. #endif